import { defineStore } from 'pinia'
import { getUserInfo } from '../../api/roles'

const SiteLayout = () => import('../../layout/index.vue')
// 从文件系统导入多个模块: 将页面级组件都导入进来
const pageModules = import.meta.glob('../../views/**/*.vue')
const pid2tree = (data:any) => {
  const result:any[] = []
  const map = {}
  data.forEach((item:any) => {
    map[item.id] = item
  })
  data.forEach((item:any) => {
    const parent = map[item.pid]
    if (parent) {
      (parent.children || (parent.children = [])).push(item)
    } else {
      result.push(item)
    }
  })
  return result
}
/**
 * 生成动态路由
 * @param {*} menu
 */
const generateDynamicRoutes = (menuTree:any) => menuTree.map((menu:any) => {
  const route = {
    path: menu.index,
    name: menu.name,
    icon: menu.icon,
    component: pageModules[`/src/views${menu.rule}.vue`] ?? SiteLayout, // /src/views/user.vue  /src/views/dashboard.vue
  }
  console.log(menu.childMenu);
  
  if (menu.childMenu.length > 0) {
    route.childMenu = generateDynamicRoutes(menu.childMenu)
  }

  return route
})

const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    userInfo: null, // 基本信息
    role: null, // 角色
    routes: [], // 动态路由信息
    menus: [], // 菜单信息
    routerRoles: ['/', '/:pathMatch(.*)*'], // 权限白名单
    // hostHead: import.meta.env.VITE_BASE_API + "/goodsItem/"
    hostHead: import.meta.env.VITE_BASE_API + "/file/"
  }),
  actions: {
    //   修改用户信息
    SET_USERINFO(payload:any) {
      this.userInfo = payload
    },
    SET_ROLE(payload:any) {
      this.role = payload
    },
    /**
     * 设置菜单
     */
    SET_MENUS(payload:any) {
      this.menus = payload
    },
    /**
     * 设置路由信息
     */
    SET_ROUTES(payload:any) {
      this.routes = payload
    },
    /**
     * 重置用户状态信息
     */
    RESET() {
      this.userInfo = null
      this.role = null
      this.routes = []
      this.menus = []
    },
    /**
     * 处理获取用户基本信息逻辑，更改状态数据
     * @param ctx 上下文对象，结构与 store 基本一致
     */
    async getUserInfoAction() {
      // 发送网络请求，获取用户基本信息
      // const { userInfo, roles } = await getUserInfo()
      const route = await getUserInfo()

      // 如果有用户基本信息，则将状态中的用户基本信息字段进行修改
      // this.SET_USERINFO(userInfo)
      // this.SET_ROLE(roles?.[0])
      this.SET_ROLE(route)

      return { role: route }
    },
    // 根据角色信息动态生成路由与菜单信息
    async generateRoutesAndMenus(role:any) {
      // 根据角色中的权限生成菜单数据
      // const menuPermissions = role?.permissions?.filter((permission:any) => permission.type === 1)
      // console.log('menuPermissions', menuPermissions)
      // menuPermissions.forEach((item:any) => { this.routerRoles.push(item?.rule) })
      // console.log('routerRoles', this.routerRoles)

      // 将角色中菜单权限数组（扁平结构）转换为树结构
      // const menuTree = pid2tree(menuPermissions ?? [])
      // this.SET_MENUS(menuTree)
      // 根据菜单权限信息生成路由配置信息
      // console.log('menuTree:', menuTree)
      const menus = generateDynamicRoutes(role)
      console.log('生成的路由表:', menus)
      this.SET_MENUS(menus)

      return { menus }
    },
  },
  getters: {
    getUserInfo: state => state.userInfo,
    getRole: state => state.role,
    getRoutes: state => state.routes,
    getMenus: state => state.menus,
    getRouterRoles: state => state.routerRoles,
    getHostHead: state => state.hostHead,
  },
})

export default useUserStore
